<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="80px"
    >
      <el-form-item label="客户名称" prop="customerId">
        <el-select
          v-model="queryParams.customerId"
          class="!w-240px"
          clearable
          lable-key="name"
          placeholder="请选择客户"
          value-key="id"
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.name"
            :value="item.id!"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="单据编号" prop="slipNo">
        <el-input
          v-model="queryParams.slipNo"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="订单状态" prop="orderStatus">
        <el-select
          v-model="queryParams.orderStatus"
          placeholder="请选择订单状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.TRADE_ORDER_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单类型" prop="orderType">
        <el-select
          v-model="queryParams.orderType"
          placeholder="请选择订单类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.TRADE_ORDER_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="交货方式" prop="deliveryType">
        <el-select
          v-model="queryParams.deliveryType"
          placeholder="请选择交货方式"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.TRADE_DELIVERY_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!--      <el-form-item label="联系人编" prop="signContactId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.signContactId"-->
      <!--          placeholder="请输入联系人编号"-->
      <!--          clearable-->
      <!--          @keyup.enter="handleQuery"-->
      <!--          class="!w-240px"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="公司下单人" prop="signUserId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.signUserId"-->
      <!--          placeholder="请输入公司下单人"-->
      <!--          clearable-->
      <!--          @keyup.enter="handleQuery"-->
      <!--          class="!w-240px"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="收货地区" prop="areaId">
        <el-cascader
          clearable
          filterable
          v-model="queryParams.areaId"
          :options="areaList"
          :props="defaultProps"
          @keyup.enter="handleQuery"
          class="!w-300px"
          placeholder="请选择收货地区"
        />
      </el-form-item>
      <el-form-item label="下单日期" prop="orderDate" >
        <el-date-picker
          v-model="queryParams.orderDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="发货时间" prop="shipTime">
        <el-date-picker
          v-model="queryParams.shipTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="到货时间" prop="deliveryTime">
        <el-date-picker
          v-model="queryParams.deliveryTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>


      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['crm:order:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['crm:order:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['crm:order:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="我负责的" name="1" />
      <el-tab-pane label="我参与的" name="2" />
      <el-tab-pane label="下属负责的" name="3" />
    </el-tabs>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column label="订单名称" align="center" prop="orderName" />
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="单据编号" align="center" prop="slipNo" />
      <el-table-column label="客户名称" align="center" prop="customerName" />
      <el-table-column label="店铺名称" align="center" prop="storeName" />
<!--      <el-table-column label="商机编号" align="center" prop="businessId" />-->
      <el-table-column
        label="最后跟进时间"
        align="center"
        prop="contactLastTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="下单人" align="center" prop="ownerUserName" />
<!--      <el-table-column label="工作流编号" align="center" prop="processInstanceId" />-->
      <el-table-column label="审批状态" align="center" prop="auditStatus" >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CRM_AUDIT_STATUS" :value="scope.row.auditStatus" />
        </template>
      </el-table-column>
      <el-table-column label="订单类型" align="center" prop="orderType" >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.TRADE_ORDER_TYPE" :value="scope.row.orderType" />
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderStatus" >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.TRADE_ORDER_STATUS" :value="scope.row.orderStatus" />
        </template>
      </el-table-column>
      <el-table-column label="产品总金额" align="center" prop="totalProductPrice" width="140">
        <template #default="scope"> {{scope.row.totalProductPrice}} 元</template>
      </el-table-column>
      <el-table-column label="整单折扣" align="center" prop="discountPercent" />
      <el-table-column label="订单总金额" align="center" prop="totalPrice"  width="140">
        <template #default="scope"> {{scope.row.totalPrice}} 元</template>
      </el-table-column>
      <el-table-column label="联系人" align="center" prop="signContactName" />
      <el-table-column label="联系电话" align="center" prop="signContactPhone" />
<!--      <el-table-column label="下单人" align="center" prop="signUserId" />-->
      <el-table-column label="收货地区" align="center" prop="areaId" width="240">
        <template #default="scope">
          <el-cascader
            v-model="scope.row.areaId"
            :options="areaList"
            :props="defaultProps"
            class="w-1/1"
            disabled
          />
        </template>
      </el-table-column>
      <el-table-column label="收货详细地址" align="center" prop="detailAddress" width="200"/>
      <el-table-column label="交货方式" align="center" prop="deliveryType" >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.TRADE_DELIVERY_TYPE" :value="scope.row.deliveryType" />
        </template>
      </el-table-column>
      <el-table-column
        label="下单日期"
        align="center"
        prop="orderDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="发货时间"
        align="center"
        prop="shipTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="到货时间"
        align="center"
        prop="deliveryTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="销售范围" align="center" prop="salesScope" />
      <el-table-column label="代理商" align="center" prop="salesAgent" />
<!--      <el-table-column-->
<!--        label="开始时间"-->
<!--        align="center"-->
<!--        prop="startTime"-->
<!--        :formatter="dateFormatter"-->
<!--        width="180px"-->
<!--      />-->
<!--      <el-table-column-->
<!--        label="结束时间"-->
<!--        align="center"-->
<!--        prop="endTime"-->
<!--        :formatter="dateFormatter"-->
<!--        width="180px"-->
<!--      />-->

      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['crm:order:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['crm:order:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <OrderForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { DICT_TYPE, getIntDictOptions ,getStrDictOptions} from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { OrderApi, Order } from '@/api/crm/order'
import OrderForm from './OrderForm.vue'
import * as CustomerApi from "@/api/crm/customer";
import * as AreaApi from "@/api/system/area";
import { defaultProps } from '@/utils/tree'
import {TabsPaneContext} from "element-plus";

/** CRM 订单 列表 */
defineOptions({ name: 'Order' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<Order[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  orderName: undefined,
  orderNo: undefined,
  slipNo: undefined,
  customerId: undefined,
  storeId: undefined,
  businessId: undefined,
  contactLastTime: [],
  ownerUserId: undefined,
  processInstanceId: undefined,
  auditStatus: undefined,
  orderStatus: undefined,
  orderType: undefined,
  salesScope: undefined,
  salesAgent: undefined,
  orderDate: [],
  shipTime: [],
  deliveryTime: [],
  deliveryType: undefined,
  startTime: [],
  endTime: [],
  totalProductPrice: undefined,
  discountPercent: undefined,
  totalPrice: undefined,
  signContactId: undefined,
  signUserId: undefined,
  areaId: undefined,
  detailAddress: undefined,
  remark: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const activeName = ref('1') // 列表 tab
const customerList = ref<CustomerApi.CustomerVO[]>([]) // 客户列表
const areaList = ref([]) // 地区列表

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await OrderApi.getOrderPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
/** tab 切换 */
const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.sceneType = tab.paneName
  handleQuery()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await OrderApi.deleteOrder(id)
    message.success(t('common.delSuccess'))
    currentRow.value = {}
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除CRM 订单 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await OrderApi.deleteOrderList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Order[]) => {
  checkedIds.value = records.map((item) => item.id!);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await OrderApi.exportOrder(queryParams)
    download.excel(data, 'CRM 订单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  getList()
  // 获得客户列表
  customerList.value =  await CustomerApi.getCustomerSimpleList()

  // 获得地区列表
  areaList.value = await AreaApi.getAreaTree()
})
</script>
